const musicContainer = document.getElementById('music-container') as HTMLDivElement
const playBtn = document.getElementById('play') as HTMLButtonElement
const prevBtn = document.getElementById('prev') as HTMLButtonElement
const nextBtn = document.getElementById('next') as HTMLButtonElement

const audio = document.getElementById('audio') as HTMLAudioElement
const title = document.getElementById('title') as HTMLHeadingElement
const cover = document.getElementById('cover') as HTMLImageElement

const progress = document.getElementById('progress') as HTMLDivElement
const progressContainer = document.getElementById('progress-container') as HTMLDivElement

// Song titles
const songs = ['hey', 'summer', 'ukulele']

// keep track of song
let songIndex = 2

// Initially load song details into DOM
loadSong(songs[songIndex])

// Update song detail
function loadSong(song: string) {
  title.innerText = song
  cover.src = `img/${song}.jpg`
  audio.src = `music/${song}.mp3`
}

// Play song
function playSong() {
  musicContainer.classList.add('play')
  playBtn.querySelector('i.fas').classList.remove('fa-play')
  playBtn.querySelector('i.fas').classList.add('fa-pause')

  audio.play()
}

// Pause song
function pauseSong() {
  musicContainer.classList.remove('play')
  playBtn.querySelector('i.fas').classList.remove('fa-pause')
  playBtn.querySelector('i.fas').classList.add('fa-play')

  audio.pause()
}

// Previous song
function prevSong() {
  songIndex--
  if (songIndex < 0) {
    songIndex = songs.length - 1
  }
  loadSong(songs[songIndex])
  playSong()
}

// Next song
function nextSong() {
  songIndex++
  if (songIndex > songs.length - 1) {
    songIndex = 0
  }
  loadSong(songs[songIndex])
  playSong()
}

// Update progress bar
function updateProgress(e) {
  const { duration, currentTime } = e.srcElement
  const progressPercent = (currentTime / duration) * 100
  progress.style.width = `${progressPercent}%`
}

// Set progress bar
function setProgress(e) {
  const width = this.clientWidth
  const clickX = e.offsetX
  const duration = audio.duration

  audio.currentTime = (clickX / width) * duration
}

// Add event listener
playBtn.addEventListener('click', () => {
  const isPlaying = musicContainer.classList.contains('play')
  if (isPlaying) {
    pauseSong()
  } else {
    playSong()
  }
})
prevBtn.addEventListener('click', prevSong)
nextBtn.addEventListener('click', nextSong)

progressContainer.addEventListener('click', setProgress)
audio.addEventListener('timeupdate', updateProgress)
audio.addEventListener('ended', nextSong)
